<?php
namespace app\common\model;


use app\common\service\TimeActivity;
use think\facade\Db;
use think\Model;
use think\model\concern\SoftDelete;
use think\Paginator;

class MerchantModel extends BaseModel
{
    use SoftDelete;
    protected $table = 'merchant';

    public function getImageAttr($value)
    {
        return empty($value)?[]:explode(',',$value);
    }

    public function getLocationAddrAttr($value){
        $province = $this['province'];
        $city = $this['city'];
        $area = $this['area'];
        $locationAddr = "";
        if(!empty($province)){
            $locationAddr .=$province.'/';
            if(!empty($city)){
                $locationAddr .=$city.'/';
            }
            if(!empty($area)){
                $locationAddr .=$area;
            }
        }
        return $locationAddr;
    }

    public function getStartTimeAttr($value)
    {
        return empty($value)?'':substr($value,0,5);
    }

    public function getEndTimeAttr($value)
    {
        return empty($value)?'':substr($value,0,5);
    }

    //商品封面图
    public  function getCoverImgAttr($value,$data)
    {
        return empty($this['img'])?'':$this['img'][0];
    }


    //用户密码
    protected function setPasswordAttr($value)
    {
        if(empty($value)){
            return '';
        }
        $salt = rand(1000,9999);
        $this->setAttr('salt',$salt);
        return self::generatePwd($value,$salt);
    }

    //获取冻结金额
    public function closeMoney()
    {
        $hour = SysSettingModel::getContent('money','withdraw_hour');
        if(empty($hour)){
            return 0;
        }
        $time = time() - $hour*3600;
        $money = MerchantLogsModel::where([
            ['mid','=',$this['id']],
            ['type','=',1],
            ['m_type','in',[0,1,2]],
            ['create_time','>',$time]
        ])->sum('money');
        return $money;
    }

    //hide_phone
    public function getHidePhoneAttr($value,$data=[])
    {
        $phone = $data['phone']??'';
        return empty($phone)?'':substr_replace($phone,'****',4,4);
    }
    public function getImgAttr($value,$data)
    {
        $value = empty($value)?[]:explode(',',$value);

        return $value;
    }

    public function getLngLatAttr($value,$data)
    {
        $lng = $data['lng']??'';
        $lat = $data['lat']??'';
        return $lng.','.$lat;
    }


    public function getStoreStatusIntroAttr($value,$data)
    {
        $start_time = $data['start_time'];
        $end_time = $data['end_time'];
        $store_status = $this->getAttr('store_status');
        if($store_status==-1){
            return '未在营业时间范围内:'.substr($start_time,0,5).'~~'.substr($end_time,0,5).'';
        }else{
            return self::getPropInfo('fields_status',$store_status,'name');
        }

    }



    public function getStoreStatusAttr($value,$data)
    {
        $status = $data['is_open']??0;
        if($status==1){
            $start_time = $data['start_time'];
            $end_time = $data['end_time'];
            $current_time = date('H:i:s');
            if($start_time>$end_time){
                if($current_time<$start_time && $current_time>$end_time){
                    // if('00:00:00'<$end_time){

                    // }else{
                    //未在营业时间内
                    $status = -1;
                    // }

                }
            }elseif($start_time<$end_time){
                if($current_time<$start_time || $current_time>$end_time){
                    //未在营业时间内
                    $status = -1;
                }
            }else{
                //24小时
                $status = 1;
            }

        }
//        dump($start_time,$end_time,$current_time,$status);exit;

        return $status;
    }

    public static function getAllList()
    {
        $list = [];
        self::select()->each(function($item)use(&$list){
            array_push($list,[
                'id'=>$item['id'].'',
                'name'=>$item['name'],
            ]);
        });
        return $list;
    }

    /**
     * 获取商品数据
     * @param array $input_data 请求内容
     * @param int|null $limit 页面条数
     * @param UserModel|null $user_model 用户模型
     * @throws
     * @return \think\Paginator
     * */
    public static function getPageData(array $input_data=[])
    {
        $lng = request()->_u_lng;   //经度
        $lat = request()->_u_lat;   //纬度

        $limit = $input_data['limit']??null;

        $where = [];
        if(isset($input_data['id'])){
            $where[]  =['id','=',$input_data['id']];
        }



        $active_state = $input_data['activeCertState']??'cert_all';
        if($active_state=='cert_have')
            $where[] =['cert_img','not null',''];
        elseif($active_state=='cert_not')
            $where[] =['cert_img','null',''];

        $active_state = $input_data['activeShopState']??'auth_all';
        if($active_state=='shop_have')
            $where[] =['is_open','=',1];
        elseif($active_state=='shop_not')
            $where[] =['is_open','=',2];

        //站点信息
        $typeActivity = $input_data['typeActivity']??'';
        if($typeActivity=='network')
            $where[] =['type','=',0];
        elseif($typeActivity=='operate')
            $where[] =['type','=',1];
        elseif($typeActivity=='company')
            $where[] =['type','=',2];


        $keyword = trim($input_data['keyword']??'');
        !empty($keyword) && $where[] = ['name','like','%'.$keyword.'%'];



        if(app()->http->getName()!='admin' ){
            $where[] = ['is_platform','=',0];
            if(!isset($input_data['ignore_status'])){
                $where[] = ['status','=',1];
            }
        }
        //推荐
        $is_up = $input_data['is_up']??0;
        if(!empty($is_up)){
            $where[] = ['is_up','=',$is_up];
        }

        //事件范围查询
        if(!empty($input_data['search_date']) && is_array($input_data['search_date']) && count($input_data['search_date'])==2){
            $input_data['start_date'] = $input_data['search_date'][0];
            $input_data['end_date'] = $input_data['search_date'][1];
        }
        //按时间查询
        $start_date = empty($input_data['start_date'])?'':trim($input_data['start_date']);
        $start_time = empty($start_date)?'':strtotime($start_date);
        $end_date = empty($input_data['end_date'])?'':trim($input_data['end_date']);
        $end__time = empty($end_date)?'':strtotime('+1 day',strtotime($end_date));
        if(!empty($start_time) && !empty($end__time)){
            $where[] = ['create_time','>=',$start_time];
            $where[] = ['create_time','<=',$end__time];
        }elseif(!empty($start_time)){
            $where[] = ['create_time','>=',$start_time];
        }elseif(!empty($end__time)){
            $where[] = ['create_time','<=',$end__time];
        }



        if(isset($input_data['manager_mch_ids'])){
            if(empty($input_data['manager_mch_ids'])){
                return Paginator::make(null,1,1,0);
            }
            $where[] = ['id','in',$input_data['manager_mch_ids']];
        }
        //处理排序
        $limit_order_field = ['sort','sold_num','views','update_time','distance_m'];
        $order_field = $input_data['order_field']??'';
        $order_field = !in_array($order_field,$limit_order_field)?'sort':$order_field;
        $order_sort = $input_data['order_sort']??'';
        $order_sort = $order_sort=='desc'?'desc':'asc';
        $order = $order_field.' '.$order_sort;

        return self::with([])->where($where)->order($order)->paginate($limit);
    }

    /**
     * 修改用户数据
     * @param $input_data array
     * @throws
     * */
    public function modifyInfo(array $input_data=[])
    {
        if(empty($input_data)) throw new \Exception('数据异常');
        if(isset($input_data['password'])){
            if(empty($input_data['password'])) throw new \Exception('请输入密码');
            if(strlen($input_data['password'])<6) throw new \Exception('密码长度不得低于6位');
        }
        $this->readonly(['money','integral','f_uid1','phone']);
        $this->setAttrs($input_data);

        $this->save();
    }


    /**
     * 处理用户登录
     * @param array $input_data
     * @throws
     * @return array|self
     * */
    public static function handleLogin(array $input_data = [])
    {
        $account = $input_data['account']??'';
        $password=$input_data['password']??'';
        if(app()->http->getName()=='merchant'){
            $verify = $input_data['verify']??'';
            if (!captcha_check($verify)) throw new \Exception('验证码错误');
            if (empty($account))  throw new \Exception('用户名不能为空');
            if (empty($password ))  throw new \Exception('密码不能为空');
            $model = self::where('phone',$account)->find();
            if (!$model)  throw new \Exception('请检查账号是否正确');
            //判断密码是否正确
            if(self::generatePwd($password,$model['salt'])!=$model->password) throw new \Exception('用户名或密码错误');

        }else{
            if(isset($input_data['verify'])){
                $verify = $input_data['verify']??'';
                if(empty($verify)) throw new \Exception("请输入验证码");
                $model = self::where(["phone"=>$account])->find();
                if(empty($model)) throw new \Exception("手机号未注册");
                SmsModel::validVerify(7,$account,$verify);

            }else{
                if(empty($account)) throw new \Exception("请输入账号");
                if(empty($password)) throw new \Exception("请输入密码");
                $model = self::where(["phone"=>$account])->find();
                if(empty($model)) throw new \Exception("用户名或密码错误");
                if(self::generatePwd($password,$model['salt'])!=$model['password']) throw new \Exception("用户名或密码错误:");
            }
        }



        if($model['status']!=1) throw new \Exception("账号已被禁用");
        //更新登录ip
        $model->ip = request()->ip();
        $model->save();
        return $model;

    }

    //找回密码
    public static function forget(array $input_data = [])
    {
        if(empty($input_data['phone'])) throw new \Exception('请输入手机号');
        if(empty($input_data['password'])) throw new \Exception('请输入密码');
        if(empty($input_data['verify'])) throw new \Exception('请输入验证码');
        if(strlen($input_data['password'])<6) throw new \Exception('密码不得低于6位');
        if(!valid_phone($input_data['phone'])) throw new \Exception('请输入正确的手机号码');

        SmsModel::validVerify(8,$input_data['phone'],$input_data['verify']);

        $where_check = [];
        $where_check[] = ['phone','=',$input_data['phone']];
        $model = self::where($where_check)->find();
        if(!$model) throw new \Exception('手机号未注册,请检查手机号');
        $model->setAttr('password',$input_data['password']);
        $model->save();
        return $model;
    }


    //保存用户
    public static function handleSaveData(array $input_data = [])
    {
        if(empty($input_data['password'])){
            unset($input_data['password']);
        }
        if(empty($input_data['name'])) throw new \Exception('请输入名字');
        if(empty($input_data['phone'])) throw new \Exception('请输入手机号');
        if(!valid_phone($input_data['phone'])) throw new \Exception('请输入正确的手机号码');
        if(empty($input_data['logo'])) throw new \Exception('请上传logo图片');
        if(empty($input_data['img'])) throw new \Exception('请上传门店图片');
        /*if(empty($input_data['cert_img'])) throw new \Exception('请上传证书图片');*/
        if(isset($input_data['password']) && strlen($input_data['password'])<6) throw new \Exception('密码不得低于6位');

        if(!empty($input_data['money']) && $input_data['money']<0) throw new \Exception('用户余额不得低于 0');
        $where_check = [];
        $where_check[] = ['phone','=',$input_data['phone']];
        if(!empty($input_data['id'])){
            $where_check[] = ['id','<>',$input_data['id']];
        }else{
            $input_data["start_time"] = date("Y-m-d H:i:s",time());
        }

        if(self::where($where_check)->find()) throw new \Exception('手机号已被注册，请更换手机号');
        if(!empty($input_data["start_time"]) && !empty($input_data["end_time"]) && $input_data['end_time']!='00:00'){
//            if($input_data["end_time"] <= $input_data["start_time"])throw new \Exception('结束时间有误');
        }
        $input_data['cert_img'] = empty($input_data['cert_img'])?'':(is_array($input_data['cert_img'])?implode(',',$input_data['cert_img']):$input_data['cert_img']);
        $input_data['img'] = empty($input_data['img'])?'':(is_array($input_data['img'])?implode(',',$input_data['img']):$input_data['img']);

        $locationAddr = empty($input_data['location_addr'])?'':$input_data['location_addr'];

        $locationAddr_arr = explode("/",$locationAddr);
        if(count($locationAddr_arr)!=3) throw new \Exception('请选择地址');
        $input_data['province'] = $locationAddr_arr[0];
        $input_data['city'] = $locationAddr_arr[1];
        $input_data['area'] = $locationAddr_arr[2];



        unset($input_data["create_time"]);

        $f_mch1 = empty($input_data['f_mch1'])?0:$input_data['f_mch1'];
        if(!empty($f_mch1)){
            $up_mch_model = self::find($f_mch1);
            if(empty($up_mch_model)) throw new \Exception('隶属商家不存在,请重新选择');

        }
        $input_data['f_mch1'] = isset($up_mch_model)?$up_mch_model['id']:null;
        $input_data['f_mch2'] = isset($up_mch_model)?$up_mch_model['f_mch1']:null;
        $input_data['f_mch3'] = isset($up_mch_model)?$up_mch_model['f_mch2']:null;
        $input_data['f_mch_all'] = isset($up_mch_model)?(empty($up_mch_model['id']) ? null : $up_mch_model['id'].(empty($up_mch_model['f_mch_all'])?'':','.($up_mch_model['f_mch_all']))) :null;
        //店铺类型
        $input_data['type']= empty($input_data['type']) ? 0 : $input_data['type'];


        (new self())->actionAdd($input_data);
    }

    public static function handleDel(array $input_data = [])
    {
        $id = $input_data['id']??0;
        if(empty($id)) throw new \Exception("参数异常:id");
        $merchant_model = self::find($id);
        if(empty($merchant_model)) throw new \Exception("商家不存在或已被删除");
        $merchant_model->setAttr('delete_time',time());
        $merchant_model->save();
        //删除绑定用户状态
        if(!empty($merchant_model['uid'])){
            UserModel::where(['id'=>$merchant_model['uid']])->update(['is_mch'=>0]);
        }
    }

    public static function onBeforeInsert(Model $model)
    {
        if(empty($model['logo'])) $model->setAttr('logo',request()->domain().'/assets/logo.png');
        if(empty($model['img'])) $model->setAttr('img',request()->domain().'/assets/logo.png');
    }

    public static function onAfterUpdate(Model $model)
    {
        //我的id
        $id = (string)$model['id'];
        $change_data = $model->getChangedData();
        if(array_key_exists('f_mch1',$change_data)){
            //我的之邀信息
            $f_mch_all = empty($model['f_mch_all'])?[]:explode(',',$model['f_mch_all']);
            //直邀发生变化
            $max_len = 3;
            //查询我邀请的用户
            self::field('*,find_in_set('.$id.',f_mch_all) as f_index')->whereRaw(Db::raw('find_in_set('.$id.',f_mch_all)>0'))->select()
                ->each(function($item)use($max_len,$model,$f_mch_all){
                    $f_index = $item['f_index'];
//                    $f_index_next = $f_index+1;
//                    if($f_index_next < $max_len){
//                        for ($i = $f_index_next ; $i <= $max_len; $i++){
//                            $key = 'f_mch'.$i;
//                            $val_key = 'f_mch'.($i-1);
//                            $item->setAttr($key , $model[$val_key] );
//                        }
//                    }
                    $item_f_mch_all = empty($item['f_mch_all']) ? [] : explode(',',$item['f_mch_all']);
                    $item_f_mch_all = array_slice($item_f_mch_all,0,$f_index);
                    $last_all = array_merge($item_f_mch_all,$f_mch_all);
                    $item->setAttr('f_mch_all',implode(',', $last_all));
                    for ($i = 1 ; $i <= $max_len; $i++){
                        $key = 'f_uid'.$i;
                        $item->setAttr($key , $last_all[$i-1]??null );
                    }
                    $item->setAttr('f_uid1',implode(',',$last_all));
                    $item->save();
                });

        }
    }

    public function apiDetailInfo()
    {
        return array_merge($this->apiNormalInfo(),[
            'ser_content'=>$this['open_time'],
        ]);
    }

//用户注册
    public static function register(array $input_data = [])
    {

        if(empty($input_data['phone'])) throw new \Exception('请输入手机号');
        if(empty($input_data['password'])) throw new \Exception('请输入密码');
        if(strlen($input_data['password'])<6) throw new \Exception('密码不得低于6位');
        if(!valid_phone($input_data['phone'])) throw new \Exception('请输入正确的手机号码');

//        SmsModel::validVerify(0,$input_data['phone'],$input_data['verify']);
        $where_check = [];
        $where_check[] = ['phone','=',$input_data['phone']];
        if(self::where($where_check)->find()) throw new \Exception('手机号已被注册，请更换手机号');

        $model=(new self())->actionAdd($input_data);
        return $model;
    }

    public function apiFullInfo()
    {
        $data = [
            'status_bool' => $this['status']==1,
            'location_addr' => $this['location_addr'],
            'status' => $this['status'],
            'status_name' => self::getPropInfo('fields_status',$this['status'],'name'),
            'type' => $this['type'],
            'type_name' => self::getPropInfo('fields_type',$this['type'],'name'),
            'is_open'=>$this['is_open'],
            'create_time' => $this['create_time'],
            'update_time' => $this['update_time'],
            'coordinate' => $this['lng'] . ",". $this['lat'],

            'company_cert_img'=>$this['company_cert_img'],

        ];
        if(app()->http->getName()=='admin'){
            $data['money'] = (string)$this['money'];
            $data['order_per'] = $this['order_per'];
            $data['is_up'] = (int)$this['is_up'];
            $data['f_mch1'] = (int)$this['f_mch1'];
        }


        return array_merge($this->apiNormalInfo(),$data);
    }
    public function apiNormalInfo()
    {


        return [
            'id' => $this['id'],
            'cid' => (int)$this['cid'],
            'uid' => (string)$this['uid'],
            'name' => (string)$this['name'],
            'contact_name' => (string)$this['contact_name'],
            'logo' => (string)$this['logo'],
            'img' => $this['img'],
            'intro' => (string)$this['intro'],
            'customer_tel' => (string)$this['customer_tel'],
            'phone' => (string)$this['phone'],
            'addr' => (string)$this['addr'],
            "lng" => $this["lng"],
            "lat" => $this["lat"],



        ];
    }




}